package com.pt.config;

import com.pt.security.JwtAuthenticationFilter;
import com.pt.security.JwtAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationProvider jwtAuthenticationProvider;
    
    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            // 认证相关接口
            .antMatchers("/api/auth/**").permitAll()
            // 公共接口，无需认证
            .antMatchers("/api/public/**").permitAll()
            // Tracker相关接口（announce和scrape必须允许无认证访问）
            .antMatchers("/api/announce").permitAll()
            .antMatchers("/api/scrape").permitAll()
            // Knife4j和Swagger相关路径
            .antMatchers("/doc.html").permitAll()
            .antMatchers("/swagger-ui.html").permitAll()
            .antMatchers("/swagger-resources/**").permitAll()
            .antMatchers("/v2/api-docs").permitAll()
            .antMatchers("/v3/api-docs").permitAll()
            .antMatchers("/webjars/**").permitAll()
            .antMatchers("/favicon.ico").permitAll()
            // 静态资源
            .antMatchers("/css/**", "/js/**", "/images/**").permitAll()
            .antMatchers("/avatars/**").permitAll()
            // 管理员接口
            .antMatchers("/api/admin/**").hasAnyRole("ADMIN", "ROLE_ADMIN")
            // 其他所有API接口都需要认证（包括/api/requests等）
            .anyRequest().authenticated();

        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(jwtAuthenticationProvider);
    }
}